package jaux.message.codec;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import jaux.message.codec.annotation.ByteMessageField;
import jaux.message.codec.annotation.DownlinkByteMessage;
import jaux.message.codec.utils.MessageClassUtils;

public class ByteMessageEncoder implements MessageEncoder {

	private static final Logger logger = LoggerFactory.getLogger(ByteMessageEncoder.class);

	@Override
	public String encode(Object message) {
		String hex = null;
		if (message == null)
			return null;
		Class clz = message.getClass();
		List<Field> fields = MessageClassUtils.getMessageField(clz);
		/*
		 * 解析字节数据到需要赋值的字段上
		 */
		if (fields != null && fields.size() > 0) {
			ByteMessage sa = new ByteMessage();
			for (Field fi : fields) {
				transPropertyValue(message, sa, fi);
			}
			hex = sa.toHex();
		}
		return hex;
	}

	private void transPropertyValue(Object message, ByteMessage sa, Field fi) {
		final ExpressionParser parser = new SpelExpressionParser(); 
		final ByteMessageField annotation = fi.getAnnotation(ByteMessageField.class);
		String bmfExp = annotation.value();
		if(StringUtils.isBlank(bmfExp))
			bmfExp = annotation.encoder();
		Object fieldVal = MessageClassUtils.getFieldValue(message, fi);
		sa.setVar(fi.getName(), fieldVal);
		sa.focusVar(fi.getName());
		parser.parseExpression(bmfExp).getValue(sa);
		sa.blurVar();
	}

}
